package com.tanhua.admin.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.api.*;
import com.tanhua.config.UserHolder;
import com.tanhua.result.Result;
import com.tanhua.sso.pojo.Comment;
import com.tanhua.sso.pojo.Movement;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.pojo.Video;
import com.tanhua.sso.vo.*;
import com.tanhua.util.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ManageService {

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private VideoServiceApi videoServiceApi;

    @DubboReference
    private MovementsService movementsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private CommentsServiceApi commentsServiceApi;


    //用户数据翻页
    public Result selectPage(Integer page, Integer pagesize) {
        List<ManageUsersVo> manageUsersVoList=new ArrayList<>();
        Page<UserInfo> page1=userInfoService.selectPage(page,pagesize);
        //获取用户信息
        if (ObjectUtil.isNotEmpty(page1.getRecords())){
            for (UserInfo record : page1.getRecords()) {
                //封装
                ManageUsersVo manageUsersVo = ManageUsersVo.init(record);
                String redis = redisTemplate.opsForValue().get(Constants.FREEZE_USER + record.getId());
                //判断账号状态
                if (StrUtil.isNotEmpty(redis)){
                    manageUsersVo.setUserStatus("2");
                }
                manageUsersVoList.add(manageUsersVo);
            }
        }
        Integer pages=(manageUsersVoList.size()/pagesize)+1;
        return new Result(Convert.toInt(page1.getTotal()),pagesize,pages,page,manageUsersVoList);
    }

    //根据id查询用户详情
    public ResponseEntity findById(Long userId) {
        UserInfo info = userInfoService.selectUser(userId);
        String redis = redisTemplate.opsForValue().get(Constants.FREEZE_USER + userId);
        //判断账号状态
        if (StrUtil.isNotEmpty(redis)){
            info.setUserStatus("2");
        }
        return ResponseEntity.ok(info);
    }


    //视频记录翻页
    public Result findAllVideos(Integer page, Integer pagesize, Long uid) {
        List<Video> videoList = videoServiceApi.selectPage(page, pagesize, uid);
        UserInfo userInfo = userInfoService.selectUser(uid);
        if (ObjectUtil.isEmpty(userInfo)){
            throw new BusinessException("信息查看异常");
        }
        List<ManageVvideosVo> list=new ArrayList<>();
        for (Video video : videoList) {
            ManageVvideosVo manageVvideosVo = ManageVvideosVo.inti(video, userInfo);
            list.add(manageVvideosVo);
        }
        Integer pages=(list.size()/pagesize)+1;
        return new Result(list.size(),pagesize,pages,page,list);
    }

    //分页查看动态
    public Result findAllMovements(Integer page, Integer pagesize, Long uid, String state) {
        //查看动态
        ResultVo<Movement> page1 = movementsService.page(page, pagesize, uid, state);
        List<Movement> items = page1.getItems();
        List<ManageMovementsVo> list=new ArrayList<>();
        //封装
        if (ObjectUtil.isNotEmpty(items)){
            for (Movement item : items) {
                UserInfo userInfo = userInfoService.selectUser(item.getUserId());
                ManageMovementsVo manageMovementsVo = ManageMovementsVo.init(userInfo, item);
                //判断状态
                if ("''".equals(state)){
                    manageMovementsVo.setState(null);
                }else {
                    manageMovementsVo.setState(Convert.toStr(state));
                }
                list.add(manageMovementsVo);
            }
        }
        Result result=new Result();
        BeanUtils.copyProperties(page1,result,"items");
        result.setItems(list);
        return result;
    }

    //用户冻结
    public Map userFreeze(Map params) {
        Integer freezingTime = Integer.valueOf(params.get("freezingTime").toString());
        Integer userId = (Integer) params.get("userId");
        int days = 0;
        //冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
        if (freezingTime == 1) {
            days = 3;
        }
        if (freezingTime == 2) {
            days = 7;
        }
        if (freezingTime == 3) {
            days = -1;
        }
        String value = JSON.toJSONString(params);
        redisTemplate.opsForValue().set(Constants.FREEZE_USER+userId,value,days*10, TimeUnit.SECONDS);
        Map map = new HashMap();
        map.put("message","冻结成功");
        return map;
    }

    //用户解冻
    public Map userUnfreeze(Map params) {
        Integer userId = (Integer) params.get("userId");
        //理由
        String reasonsForThawing = (String) params.get("reasonsForThawing");
        redisTemplate.delete(Constants.FREEZE_USER+userId);
        Map map = new HashMap();
        map.put("message","解冻成功");
        return map;
    }

    //动态详情
    public AdminMovementsVo selectById(String movementId) {
        //获取当前用户id
        Long userId = AdminHolder.getUserId();
        UserInfo userInfo = userInfoService.selectUser(userId);
        //获取动态信息
        Movement movementByid = movementsService.getMovementByid(movementId);
        AdminMovementsVo adminMovementsVo=new AdminMovementsVo();
        BeanUtils.copyProperties(userInfo,adminMovementsVo);
        BeanUtils.copyProperties(movementByid,adminMovementsVo);
        adminMovementsVo.setId(movementByid.getId().toHexString());
        adminMovementsVo.setImageContent(movementByid.getMedias());
        adminMovementsVo.setCreateDate(System.currentTimeMillis());
        return adminMovementsVo;
    }

    //评论列表翻页
    public Result comments(Integer page, Integer pagesize, String messageID) {
        //查看评论
        ResultVo<Comment> resultVo=commentsServiceApi.selectPage(page,pagesize,messageID);
        List<Comment> items = resultVo.getItems();
        List<AdminCommentsVo> commentVoList=new ArrayList<>();
        if (ObjectUtil.isNotEmpty(items)){
            for (Comment item : items) {
                UserInfo userInfo = userInfoService.selectUser(item.getUserId());
                AdminCommentsVo adminCommentsVo=new AdminCommentsVo();
                adminCommentsVo.setId(item.getId().toHexString());
                adminCommentsVo.setUserId(item.getUserId());
                adminCommentsVo.setNickname(userInfo.getNickname());
                adminCommentsVo.setCreateDate(new Date(item.getCreated()));
                adminCommentsVo.setContent(item.getContent());
                commentVoList.add(adminCommentsVo);
            }
        }
        Result result=new Result();
        BeanUtils.copyProperties(resultVo,result,"items");
        result.setItems(commentVoList);
        return result;
    }

    //审核动态
    public void pass(List<String> ids,Integer state) {
        movementsService.updatePass(ids,state);
    }
}
